package cn.jingdalei.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component // 交给容器管理
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// f6cd633f-9759-4e85-99d2-d6e554ab9673
        if(!StringUtils.isEmpty(token)){// 携带的有token 即登录成功
            // 拿到logininfo 刷新过期时间
            Object logininfo = redisTemplate.opsForValue().get(token);
            if(logininfo != null){// 重新设置过期时间
                redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 没有拿到token 登录失败 提示错误
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 获取流
        PrintWriter writer = response.getWriter();
        // {"success":false,"message":"nologin"} 展示错误信息
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        // 关流
        writer.close();
        return false;// 拦截
    }
}
